/**
 * 超级管理员企业管理控制器
 *
 * 开发人员：徐少洋
 * 开发时间：2025-11-21
 * 模块职责：提供超级管理员管理所有企业的REST API接口
 */
package com.pbl.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pbl.common.model.ApiResponse;
import com.pbl.entity.Enterprise;
import com.pbl.service.EnterpriseService;
import com.pbl.service.SuperAdminService;
import lombok.Data;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/super-admin/enterprises")
public class SuperAdminEnterpriseController {
    
    private final EnterpriseService enterpriseService;
    private final SuperAdminService superAdminService;
    private final JdbcTemplate jdbcTemplate;
    private final ObjectMapper objectMapper;
    
    public SuperAdminEnterpriseController(EnterpriseService enterpriseService,
                                         SuperAdminService superAdminService,
                                         JdbcTemplate jdbcTemplate,
                                         ObjectMapper objectMapper) {
        this.enterpriseService = enterpriseService;
        this.superAdminService = superAdminService;
        this.jdbcTemplate = jdbcTemplate;
        this.objectMapper = objectMapper;
    }
    
    /**
     * 获取所有企业列表（含统计信息）
     */
    @GetMapping
    public ApiResponse<List<Map<String, Object>>> list(@RequestAttribute("superAdminId") Long superAdminId) {
        List<Map<String, Object>> enterprises = jdbcTemplate.queryForList(
            "SELECT * FROM v_enterprise_statistics ORDER BY created_at DESC"
        );
        return ApiResponse.success(enterprises);
    }
    
    /**
     * 获取企业详情（含完整统计）
     */
    @GetMapping("/{id}")
    public ApiResponse<Map<String, Object>> get(@RequestAttribute("superAdminId") Long superAdminId,
                                                @PathVariable Long id) {
        Enterprise enterprise = enterpriseService.get(id);
        
        // 获取统计信息
        Map<String, Object> stats = jdbcTemplate.queryForMap(
            "SELECT * FROM v_enterprise_statistics WHERE enterprise_id = ?", id
        );
        
        // 获取操作日志
        List<Map<String, Object>> logs = jdbcTemplate.queryForList(
            "SELECT * FROM super_admin_logs WHERE target_type = 'enterprise' AND target_id = ? " +
            "ORDER BY created_at DESC LIMIT 20", id
        );
        
        Map<String, Object> result = new HashMap<>();
        result.put("enterprise", enterprise);
        result.put("statistics", stats);
        result.put("logs", logs);
        
        return ApiResponse.success(result);
    }
    
    /**
     * 创建新企业
     */
    @PostMapping
    public ApiResponse<Enterprise> create(@RequestAttribute("superAdminId") Long superAdminId,
                                         @Valid @RequestBody CreateEnterpriseRequest request,
                                         HttpServletRequest httpRequest) {
        Enterprise enterprise = Enterprise.builder()
            .name(request.getName())
            .creditCode(request.getCreditCode())
            .contactName(request.getContactName())
            .contactPhone(request.getContactPhone())
            .status(1)
            .remark(request.getRemark())
            .subscriptionPlan(request.getSubscriptionPlan() != null ? request.getSubscriptionPlan() : "FREE")
            .maxUsers(request.getMaxUsers() != null ? request.getMaxUsers() : 10)
            .storageQuotaMb(request.getStorageQuotaMb() != null ? request.getStorageQuotaMb() : 1024)
            .createdBySuperAdminId(superAdminId)
            .build();
        
        Enterprise created = enterpriseService.create(enterprise);
        
        // 记录日志
        try {
            String detail = objectMapper.writeValueAsString(Map.of(
                "enterpriseName", created.getName(),
                "creditCode", created.getCreditCode(),
                "subscriptionPlan", created.getSubscriptionPlan()
            ));
            superAdminService.logAction(superAdminId, "CREATE_ENTERPRISE", "enterprise", 
                created.getId(), detail,
                httpRequest.getRemoteAddr(), httpRequest.getHeader("User-Agent"));
        } catch (Exception e) {
            // 日志记录失败不影响主流程
        }
        
        return ApiResponse.success(created);
    }
    
    /**
     * 更新企业信息
     */
    @PutMapping("/{id}")
    public ApiResponse<Enterprise> update(@RequestAttribute("superAdminId") Long superAdminId,
                                         @PathVariable Long id,
                                         @Valid @RequestBody UpdateEnterpriseRequest request,
                                         HttpServletRequest httpRequest) {
        Enterprise enterprise = new Enterprise();
        enterprise.setName(request.getName());
        enterprise.setCreditCode(request.getCreditCode());
        enterprise.setContactName(request.getContactName());
        enterprise.setContactPhone(request.getContactPhone());
        enterprise.setStatus(request.getStatus());
        enterprise.setRemark(request.getRemark());
        enterprise.setSubscriptionPlan(request.getSubscriptionPlan());
        enterprise.setSubscriptionExpiresAt(request.getSubscriptionExpiresAt());
        enterprise.setMaxUsers(request.getMaxUsers());
        enterprise.setStorageQuotaMb(request.getStorageQuotaMb());
        
        Enterprise updated = enterpriseService.update(id, enterprise);
        
        // 记录日志
        try {
            String detail = objectMapper.writeValueAsString(Map.of(
                "enterpriseName", updated.getName(),
                "changes", request
            ));
            superAdminService.logAction(superAdminId, "UPDATE_ENTERPRISE", "enterprise", 
                id, detail,
                httpRequest.getRemoteAddr(), httpRequest.getHeader("User-Agent"));
        } catch (Exception e) {
            // 日志记录失败不影响主流程
        }
        
        return ApiResponse.success(updated);
    }
    
    /**
     * 删除企业
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@RequestAttribute("superAdminId") Long superAdminId,
                                    @PathVariable Long id,
                                    HttpServletRequest httpRequest) {
        Enterprise enterprise = enterpriseService.get(id);
        enterpriseService.delete(id);
        
        // 记录日志
        try {
            String detail = objectMapper.writeValueAsString(Map.of(
                "enterpriseName", enterprise.getName(),
                "creditCode", enterprise.getCreditCode()
            ));
            superAdminService.logAction(superAdminId, "DELETE_ENTERPRISE", "enterprise", 
                id, detail,
                httpRequest.getRemoteAddr(), httpRequest.getHeader("User-Agent"));
        } catch (Exception e) {
            // 日志记录失败不影响主流程
        }
        
        return ApiResponse.success(null);
    }
    
    /**
     * 获取系统总览统计
     */
    @GetMapping("/statistics/overview")
    public ApiResponse<Map<String, Object>> getOverview(@RequestAttribute("superAdminId") Long superAdminId) {
        Map<String, Object> overview = new HashMap<>();
        
        // 企业统计
        overview.put("totalEnterprises", jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM enterprises", Long.class));
        overview.put("activeEnterprises", jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM enterprises WHERE status = 1", Long.class));
        
        // 用户统计
        overview.put("totalUsers", jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM users", Long.class));
        overview.put("activeUsers", jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM users WHERE status = 1", Long.class));
        
        // 订单统计
        overview.put("totalOrders", jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM payment_orders", Long.class));
        overview.put("successOrders", jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM payment_orders WHERE status = 'SUCCESS'", Long.class));
        
        // 收入统计
        overview.put("totalRevenue", jdbcTemplate.queryForObject(
            "SELECT COALESCE(SUM(amount), 0) FROM payment_orders WHERE status = 'SUCCESS'", 
            java.math.BigDecimal.class));
        
        // 融资统计
        overview.put("totalFinancingRequests", jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM financing_requests", Long.class));
        overview.put("approvedFinancingRequests", jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM financing_requests WHERE status = 'APPROVED'", Long.class));
        
        return ApiResponse.success(overview);
    }

    /**
     * 获取指定企业的所有用户列表
     */
    @GetMapping("/{id}/users")
    public ApiResponse<List<Map<String, Object>>> getUsers(@PathVariable Long id) {
        System.out.println("DEBUG: Fetching users for enterpriseId: " + id);
        try {
            // 简化SQL，先只查基础字段，排除子查询干扰
            String sql = "SELECT u.id, u.username, u.email, u.phone, u.status, " +
                         "u.is_enterprise_admin, u.created_at, u.last_login_at " +
                         "FROM users u WHERE u.enterprise_id = ? ORDER BY u.created_at DESC";
            
            List<Map<String, Object>> users = jdbcTemplate.queryForList(sql, id);
            
            System.out.println("DEBUG: Found " + users.size() + " users.");
            
            // 手动补全角色信息（避免复杂的子查询）
            for (Map<String, Object> user : users) {
                Long userId = ((Number) user.get("id")).longValue();
                try {
                    String roles = jdbcTemplate.queryForObject(
                        "SELECT GROUP_CONCAT(r.name) FROM user_roles ur JOIN roles r ON ur.role_id = r.id WHERE ur.user_id = ?",
                        String.class, userId);
                    user.put("roles", roles);
                } catch (Exception e) {
                    user.put("roles", "");
                }
                
                // 修正 boolean/bit 类型
                Object isAdmin = user.get("is_enterprise_admin");
                if (isAdmin instanceof Boolean) {
                    user.put("is_enterprise_admin", (Boolean) isAdmin ? 1 : 0); // 统一转为数字或保持布尔，前端能处理
                }
            }
            
            return ApiResponse.success(users);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 获取指定企业的所有订单
     */
    @GetMapping("/{id}/orders")
    public ApiResponse<List<Map<String, Object>>> getOrders(@PathVariable Long id) {
        List<Map<String, Object>> orders = jdbcTemplate.queryForList(
            "SELECT * FROM payment_orders WHERE enterprise_id = ? ORDER BY created_at DESC LIMIT 100",
            id
        );
        return ApiResponse.success(orders);
    }

    /**
     * 获取指定企业的所有融资申请
     */
    @GetMapping("/{id}/financing")
    public ApiResponse<List<Map<String, Object>>> getFinancingRequests(@PathVariable Long id) {
        List<Map<String, Object>> requests = jdbcTemplate.queryForList(
            "SELECT * FROM financing_requests WHERE enterprise_id = ? ORDER BY created_at DESC",
            id
        );
        return ApiResponse.success(requests);
    }
    
    // DTO类
    @Data
    public static class CreateEnterpriseRequest {
        @NotBlank
        private String name;
        
        private String creditCode;
        private String contactName;
        private String contactPhone;
        private String remark;
        private String subscriptionPlan;
        private Integer maxUsers;
        private Integer storageQuotaMb;
    }
    
    @Data
    public static class UpdateEnterpriseRequest {
        private String name;
        private String creditCode;
        private String contactName;
        private String contactPhone;
        private Integer status;
        private String remark;
        private String subscriptionPlan;
        private LocalDateTime subscriptionExpiresAt;
        private Integer maxUsers;
        private Integer storageQuotaMb;
    }
}

